﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using System.ComponentModel;

namespace Janus.Cores.DynamicProxy.CastleDynamic.Interception
{
    /// <summary>
    /// 功能：高性能定时器
    /// 作者：luochengbang@163.com
    /// 日期：2012/6/7 11:14:28 
    /// 备注：本代码版权归Janus所有，严禁外传 
    /// </summary>
    internal class PerfTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime;
        private long freq;

        /// <summary>
        /// 构造函数
        /// </summary>
        public PerfTimer()
        {
            startTime = 0;
            stopTime  = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // 不支持高性能计数器
                throw new Win32Exception();
            }
        }

        /// <summary>
        /// 开始计时器
        /// </summary>
        public void Start()
        {
            // 来让等待线程工作
            Thread.Sleep(0);

            QueryPerformanceCounter(out startTime);
        }

        /// <summary>
        ///  停止计时器
        /// </summary>
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        /// <summary>
        /// 返回计时器经过时间(单位：秒)
        /// </summary>
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double) freq;
            }
        }
    }
}
